<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 头部警告 -->
      <el-alert title="添加商品信息" type="info" center
      :closable="false" show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs栏标签页 -->
      <el-form :model="addFormDate" :rules="addFormRules" ref="addFormRef"
      label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" tab-position="left"
        :before-leave="beforeTableLeave" @tab-click="tabClick">
          <!-- 基本信息页签 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addFormDate.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addFormDate.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addFormDate.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addFormDate.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader expand-trigger="hover" :options="goodsParams"
              v-model="addFormDate.goods_cat" @change="handleChange" :props="goodsProps">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数页签 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="(item, i) in manyTableData"
            :key="i">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item2" v-for="(item2, i) in item.attr_vals"
                :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性页签 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item, i) in onlyTableData"
            :key="i">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传区域 -->
            <el-upload
            :action="Url"
            :headers="headerObj"
            :on-success="handleSuccess"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addFormDate.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog
    title="图片预览" :visible.sync="picDialogVisible" width="50%"
    @closed="picDialogVisible=false">
      <img :src="previewUrl" alt="" style="width: 100%">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  data() {
    return {
      // 控制steps选项
      activeIndex: '0',
      // tabs页签中的表单对象
      addFormDate: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 级联选择器选中后绑定的id数组
        goods_cat: [],
        // 图片上传时的临时路径
        pics: [],
        // 添加商品的介绍
        goods_introduce: '',
        // 商品的参数（数组）,包含动态参数和静态属性
        attrs: []
      },
      // 商品分类数据
      goodsParams: [],
      // 控制tabs页签的跳转
      addCate: true,
      // 添加商品信息的校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品的名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品的价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品的重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品的重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选中商品的分类', trigger: 'blur' }
        ]
      },
      // 级联选择器的配置
      goodsProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 商品列表数据(商品参数tab需要的数据)
      manyTableData: [],
      onlyTableData: [],
      // 图片上传区
      // 上传图片的地址
      Url: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片预览的绝对路径
      previewUrl: '',
      // 设置请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制图片预览对话框的显示与隐藏
      picDialogVisible: false
    }
  },
  created() {
    this.getParamsDate()
  },
  computed: {
    cateId() {
      if (this.addFormDate.goods_cat.length === 3) {
        return this.addFormDate.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    // 获取所有商品分类
    async getParamsDate() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$http.error('获取商品分类失败')
      this.goodsParams = res.data
    },
    // 监听级联选择器选项改变
    handleChange() {
      // 只允许选择三级分类
      if (this.addFormDate.goods_cat.length !== 3) {
        this.addFormDate.goods_cat = []
      }
    },
    // 控制tabs页签切换
    beforeTableLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addFormDate.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      } else {
        return true
      }
    },
    // 控制页签切换事件
    async tabClick() {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error('获取动态参数列表失败')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTableData = res.data
        console.log(this.manyTableData)
      } else {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return false
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // 图片上传成功时触发的函数
    handleSuccess(response) {
      // 上传成功获取临时路径
      console.log(response)
      if (response.meta.status === 200) {
        const pics = { pic: response.data.tmp_path }
        this.addFormDate.pics.push(pics)
        console.log(this.addFormDate)
      }
    },
    // 点击图片进行预览，需要后端保存图片绝对路径不是临时路径
    handlePreview(file) {
      console.log(file)
      this.previewUrl = file.response.data.url
      this.picDialogVisible = true
    },
    // 点击删除图片
    handleRemove(file) {
      console.log(file)
      const pics = { pic: file.response.data.tmp_path }
      const i = this.addFormDate.pics.findIndex(x => x.pic === pics.pic)
      this.addFormDate.pics.splice(i, 1)
      console.log(this.addFormDate)
    },
    // 监听添加商品按钮
    add() {
      this.$refs.addFormRef.validate(async val => {
        if (!val) return this.$message.error('请填写必要的表单项')
        // 拷贝addFormDate
        const addForm = _.cloneDeep(this.addFormDate)
        addForm.goods_cat = addForm.goods_cat.join(',')
        // 动态参数添加到请求头的attrs数组中
        this.manyTableData.forEach(item => {
          const attr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addFormDate.attrs.push(attr)
        })
        // 静态属性添加到请求头的attrs数组中
        this.onlyTableData.forEach(item => {
          const attr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addFormDate.attrs.push(attr)
        })
        // 把addFormDate中的attrs数组赋值给addForm
        addForm.attrs = this.addFormDate.attrs
        const { data: res } = await this.$http.post('goods', addForm)
        console.log(addForm)
        console.log(res.data)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.el-button {
  margin-top: 20px;
}
</style>
